import os
import sys

from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox, QInputDialog, QLineEdit
import untitled
import store
from conftool import ConfTool
from helper import copyfile


class Example(QMainWindow):
    def __init__(self):
        self.mould_role_tmplist = None
        self.mould_roles_data = None
        self.source_role_tmplist = None
        self.target_role_tmplist = None
        self.app = QApplication(sys.argv)
        super().__init__()
        self.ui = untitled.Ui_JX3Tools()
        self.ui.setupUi(self)
        # 初始化
        self.old_role_index = None
        self.new_role_index = None
        self.roles_data = None
        self.currentSourceRoleData = None
        self.currentTargetRoleData = None
        self.currentMouldRoleData = None
        self.init_ui()

    def showmess(self):
        print()

    def get_role_data_model(self, search_str=''):
        model1 = QStandardItemModel()
        for user_data in self.roles_data:
            # 遍历每个服务器下数据
            for roles_data in user_data['user_role_data']:
                # 遍历每个角色
                for role_data in roles_data['roles']:
                    if search_str in role_data['role_name']:
                        qsitem = QStandardItem(QStandardItem(role_data['role_name']))
                        qsitem.appendColumn([QStandardItem(user_data['username']),
                                             QStandardItem(roles_data['region']),
                                             QStandardItem(roles_data['server']),
                                             QStandardItem(role_data['role_path'])])
                        model1.appendRow(qsitem)
        return model1

    def initdata(self, search_str=''):
        # store.rolelist = store.seach_roles(store.default_path if store.default_path else store.dir_path)
        self.search_mould_do()
        pass

    def search_source_do(self, search_str=''):
        self.source_role_tmplist = self.get_role_data_model(search_str)
        self.ui.listView_sourceRoles.setModel(self.source_role_tmplist)
        self.ui.listView_sourceRoles.setModelColumn(0)

    def search_target_do(self, search_str=''):
        self.target_role_tmplist = self.get_role_data_model(search_str)
        self.ui.listView_2.setModel(self.target_role_tmplist)
        self.ui.listView_2.setModelColumn(0)
        pass

    def search_mould_do(self, search_str=''):
        self.mould_role_tmplist = self.get_mould_data_model(search_str)
        self.ui.listView_mouldRoles.setModel(self.mould_role_tmplist)
        self.ui.listView_mouldRoles.setModelColumn(0)
        pass

    def get_mould_data_model(self, search_str=''):
        self.mould_roles_data = store.search_roles(store.dir_path, 'mould_data')
        mould_model = QStandardItemModel()

        for role_data in self.mould_roles_data:
            if search_str in role_data['role_name']:
                qsitem = QStandardItem(QStandardItem(role_data['role_name']))
                qsitem.appendColumn([QStandardItem(role_data['role_sect']),
                                     QStandardItem('region'),
                                     QStandardItem('server'),
                                     QStandardItem(role_data['role_path'])])
                mould_model.appendRow(qsitem)
        return mould_model
        pass

    def search_roles_click(self):
        """
        检索所有角色
        :return:
        """
        "default_path初始化会取一次config.ini，菜单open路径也会设一次，如果都没有过，则取程序当前路径"
        self.roles_data = store.get_username_dir_list(store.default_path if store.default_path else store.dir_path)
        if not self.roles_data or len(self.roles_data) == 0:
            "没有userdata路径，路径应该就是错的"
            print('config default_path none' + store.default_path)
            QMessageBox.warning(self, "警告",
                                "游戏路径有误:{}\n请先通过menu-open打开游戏路径再检索".format(store.default_path),
                                QMessageBox.Ok)
            # store.default_path = config.get('DEFAULT', 'GamePath')
            return False
        else:
            # 这里注意可能需要清空搜索栏，不然二次使用可能展示数据不全，误导用户以为数据不对
            self.search_source_do()
            self.search_target_do()
            # self.search_mould_do()

    def menu_click_success(self):
        file_name = QFileDialog.getExistingDirectory(self, "open a folder",
                                                     store.default_path if store.default_path else store.dir_path)
        store.default_path = file_name
        if store.default_path:
            config.update_config('DEFAULT', 'GamePath', store.default_path)
        print(file_name)

    def selectlistitem(self, index):
        self.currentSourceRoleData = self.source_role_tmplist.item(index.row(), 0)
        infostr = '用户名:{}\n所属账号:{}\n所在区服:{} - {}\n数据目录:{}'.format(
            self.currentSourceRoleData.text(), self.currentSourceRoleData.child(0).text(),
            self.currentSourceRoleData.child(1).text(),
            self.currentSourceRoleData.child(2).text(), self.currentSourceRoleData.child(3).text())
        print(infostr)
        # infostr = '用户名:{rolename}\n所属账号:{username}\n所在区服:{server} - {area}\n数据目录:{datafilepath}'.format(
        #     rolename=self.currentSourceRoleData[0], username=self.currentSourceRoleData[1],
        #     server=self.currentSourceRoleData[2],
        #     area=self.currentSourceRoleData[3], datafilepath=self.currentSourceRoleData[5])
        self.ui.lineEdit.setText(self.currentSourceRoleData.text())
        self.ui.plainTextEdit_souseInfo.setPlainText(infostr)
        pass

    def selectlist2item(self, index):
        self.currentTargetRoleData = self.target_role_tmplist.item(index.row())
        infostr = '用户名:{}\n所属账号:{}\n所在区服:{} - {}\n数据目录:{}'.format(
            self.currentTargetRoleData.text(), self.currentTargetRoleData.child(0).text(),
            self.currentTargetRoleData.child(1).text(),
            self.currentTargetRoleData.child(2).text(), self.currentTargetRoleData.child(3).text())
        print(infostr)
        self.ui.lineEdit_2.setText(self.currentTargetRoleData.text())
        self.ui.plainTextEdit_targetInfo.setPlainText(infostr)
        pass

    def select_mould_list_item(self, index):
        self.currentSourceRoleData = self.mould_role_tmplist.item(index.row())
        infostr = '模板名称:{}\n所属门派:{}\n数据目录:{}'.format(
            self.currentSourceRoleData.text(), self.currentSourceRoleData.child(0).text(), self.currentSourceRoleData.child(3).text())
        print(infostr)
        self.ui.lineEdit.setText(self.currentSourceRoleData.text())
        self.ui.plainTextEdit_souseInfo.setPlainText(infostr)
        pass

    def tongbu(self):
        """
        同步按键 复制文件 ps:实现不严谨，要用数据，不能用文本框内数据
        :return:
        """
        reply = QMessageBox.question(self, "确认信息",
                                     "将\n{sourceRolename}]\n同步到\n{targetRolename}]".format(
                                         sourceRolename=self.ui.plainTextEdit_souseInfo.toPlainText(),
                                         targetRolename=self.ui.plainTextEdit_targetInfo.toPlainText()),
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        if reply == 16384:

            store.old_role_file = self.currentSourceRoleData.child(3).text()
            store.new_role_file = self.currentTargetRoleData.child(3).text()
            # if not os.path.exists(store.new_role_file):
            #     print("目标目录不存在！")
            # else:
            #     print(store.old_role_file + " -> " + store.new_role_file)
            copyfile(store.old_role_file, store.new_role_file)
            print(store.old_role_file + "\n↓↓\n" + store.new_role_file)
            self.show_message(store.old_role_file + "\n↓↓↓\n" + store.new_role_file)
            QMessageBox.information(self, "提示", "应该，是同步成功了!", QMessageBox.Ok)
        else:
            QMessageBox.information(self, "提示", "取消同步!", QMessageBox.Ok)

    def set_mould_role(self):
        """
        将选择的源角色设置为模板
        """
        # print(self.currentSourceRoleData)
        print(self.currentSourceRoleData)
        value, ok = QInputDialog.getText(self, "设置模板角色", "将{}设置为模板\n请输入模板名称:".format(
            self.ui.plainTextEdit_souseInfo.toPlainText())
                                         , QLineEdit.Normal, "")
        print(ok)
        if ok:
            mouldpath = os.path.join(os.path.abspath('.'), 'mould_data', value)
            # print(os.path.abspath('.'))
            print(mouldpath)
            # 复制目录&文件
            copyfile(self.currentSourceRoleData.child(3).text(), mouldpath)
            self.search_mould_do()
            QMessageBox.information(self, "提示", "应该，是设置成功了!", QMessageBox.Ok)
        else:
            QMessageBox.warning(self, "警告", "取消设置!", QMessageBox.Ok)
            pass

    def fresh_mould_data(self):
        """刷新模板角色数据"""
        self.search_mould_do()
        pass

    def seach_mould_roles(self):
        """
        检索、设置目标角色
        """
        # self.ui.listWidget_mouldRoles

        # store.rolelist = store.seach_roles(os.path.join(store.dir_path, 'moulddata'))
        pass

    def show_message(self, msg):
        """
        确认弹窗
        :param msg:
        :return:
        """
        QMessageBox.question(self, "应该，是同步成功了!", msg)

    # ui初始化
    def init_ui(self):
        # 初始化方法，这里可以写按钮绑定等的一些初始函数
        self.ui.actionopen.triggered.connect(self.menu_click_success)
        # button 按钮事件
        self.ui.search_roles.clicked.connect(self.search_roles_click)
        self.ui.pushButton.clicked.connect(self.tongbu)
        self.ui.pushButton_setMould.clicked.connect(self.set_mould_role)
        self.ui.pushButton_fresh_mould.clicked.connect(self.fresh_mould_data)

        # lineEdit 输入框类
        self.ui.lineEdit_seach_source_str.textChanged.connect(self.search_source_do)
        self.ui.lineEdit_seach_target_str.textChanged.connect(self.search_target_do)

        # listView 列表展示
        self.ui.listView_sourceRoles.clicked.connect(self.selectlistitem)
        self.ui.listView_2.clicked.connect(self.selectlist2item)
        self.ui.listView_mouldRoles.clicked.connect(self.select_mould_list_item)

        self.initdata()

        self.show()


# 程序入口
if __name__ == '__main__':
    config = ConfTool(file="./config.ini")
    store.default_path = config.get('DEFAULT', 'GamePath')

    e = Example()

    sys.exit(e.app.exec())
